using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class app_frame_Default2 : System.Web.UI.Page
{
    //added on 10-Sep-2007
    string strPageSetId = "";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    security hdds;
    Hashtable sysVar = new Hashtable();

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        setRequestURL();//implemented by sanal on 13 Dec 2007

        this.hdds = new security();

        lbl_message.Text = "";
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        if (!IsPostBack)
        {
            //mn_main = this.hdds.load_menu(mn_main);
            //mn_main.MaximumDynamicDisplayLevels = 10;
            //lb_welcome.Text = GlobalValues.Welcome + hdds.hdfu.getUserId();
        }

        bool blnNoAccess = true;
        if (Request.QueryString["mn"] != null)
        {
            if (this.hdds.validate_menu(Request.QueryString["mn"].ToString()))
            {
                blnNoAccess = false;
            }
        }
        if (blnNoAccess)
        {
            Response.Redirect("Error.aspx");
            Response.End();
        }

        if (Request.QueryString["pgs_id"] != null)
        {
            strPageSetId = Request.QueryString["pgs_id"];
        }

        if (this.Master.FindControl("Form1") != null) //if (this.FindControl("Form1") != null)
        {
            loadAllVariables();
            GlobalValues.hsSysVar = sysVar;
            frmObj = (HtmlForm)this.Master.FindControl("Form1");//frmObj = (HtmlForm)this.FindControl("Form1")
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPageSetId);
            DynamicDisplayI DDI = new DynamicDisplayI();
            DDI.Load(strPageSetId, frmObj, dsePageInfo);
            if (!IsPostBack)
            {
                hdds.displayHelp(dsePageInfo.Tables["Page"], DDI.FindControl(frmObj.Controls, "imgHelp"));
                if (imgHelp.OnClientClick == "") imgHelp.Visible = false;
            }
            if (Request.QueryString["VMODE"] != null)
                if (Request.QueryString["VMODE"] == "1")
                {
                    setData();
                    return;
                }
            CheckEditOperation();
        }
        loadAllVariables();
    }
    private void setRequestURL()//implemented by sanal on 13 Dec 2007
    {
        if (!IsPostBack)
            hfRequestURL.Value = Request.UrlReferrer.ToString();
    }
    private void loadSystemVariables()
    {
        try
        {
            DataSet ds = new DataSet();
            DataSet dsTemp = new DataSet();
            HDDatabase db = new HDDatabase();
            ds = db.GetDataset("select * from sy_var");
            //string value = "";
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    switch (dr["sy_var_type"].ToString())
                    {
                        case "DQ"://database query
                            dsTemp = db.GetDataset(dr["sy_var_value"].ToString());
                            if (dsTemp.Tables.Count > 0)
                                sysVar.Add(dr["sy_var_name"].ToString(), dsTemp.Tables[0].Rows[0][0].ToString());
                            else
                                sysVar.Add(dr["sy_var_name"].ToString(), dr["sy_var_defaultvalue"]);
                            break;
                        case "CO"://constant
                            if (dr["sy_var_value"].ToString().Length>0)
                                sysVar.Add(dr["sy_var_name"].ToString(), dr["sy_var_value"]);
                            else
                                sysVar.Add(dr["sy_var_name"].ToString(), dr["sy_var_defaultvalue"]);
                            break;
                    }                                        
                }
            }
            ds = null;
            db = null;
        }
        catch (Exception e)
        {

        }
    }
    
    private void setData()
    {
        string sPageKey = "";
        if (Request.QueryString["PK"] != null)
            sPageKey = Request.QueryString["PK"].ToString();
        Master MA = new Master();
        bool blnStatus = MA.EditOperation(dsePageInfo, frmObj, sPageKey);
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
            Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
        }
        lblKey.Visible = false;
        lblKeyAttr.Visible = false;
        btnSave.Visible = false;
        btnUpdate.Visible = false;
        btnReset.Visible = false;
    }

    private bool CheckEditOperation()
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        if (Page.IsPostBack == false)
        {
            if (Request.QueryString["PK"] != null)
            {
                strPageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
            }
            if (IsEdit)
            {
                Master MA = new Master();
                blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
                if (blnStatus == false)
                {
                    strErrMessage = MA.ErrorMessage;
                    Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
                }
            }
        }

        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                btnSave.Visible = true;
                btnUpdate.Visible = false;
                //TextBox txtID = (TextBox)frmObj.FindControl("ContentPlaceHolder").FindControl("");
            }
        }
        else if (Request.QueryString["PK"] == null)
        {
            btnSave.Visible = true;
            btnUpdate.Visible = false;
        }
        else
        {
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }
        return blnStatus;
    }

    private bool SaveData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPageSetId, frmObj, dsePageInfo,true);

        //setDefaultValues(dseInputInfo,true);

        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }
    #region default_value_settings - can be removed if the version 06 goes ok with the primary key changes
    
    ////////private string getRandomString(int size, bool toUpperCase, ref Random random)
    ////////{
    ////////    System.Text.StringBuilder builder = new System.Text.StringBuilder();
    ////////    char ch;
    ////////    for (int i = 0; i < size; i++)
    ////////    {
    ////////        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
    ////////        builder.Append(ch);
    ////////    }
    ////////    if (toUpperCase)
    ////////        return builder.ToString().ToUpper();
    ////////    return builder.ToString();
    ////////}
    ////////private string GenerateId()
    ////////{
    ////////    long i = 1;
    ////////    foreach (byte b in Guid.NewGuid().ToByteArray())
    ////////    {
    ////////        i *= ((int)b + 1);
    ////////    }
    ////////    return string.Format("{0:x}", i - DateTime.Now.Ticks);//converts to hexa decimal
    ////////}
    ////////private string getHashKey()
    ////////{
    ////////    string temp = GenerateId();
    ////////    if (temp.Length != 16)
    ////////    {
    ////////        Random rnd = new Random();
    ////////        temp += getRandomString(16 - temp.Length, true, ref rnd);
    ////////        rnd = null;
    ////////    }
    ////////    return temp;
    ////////}
    ////////private void setDefaultValues(DataSet inputInfo,bool saveMode)//created by sanal on 13 Dec 2007
    ////////{
    ////////    //string ss = HttpContext.Current.Session["userid"].ToString().Replace("'", "''");
    ////////    string hashKey = "";
    ////////    try
    ////////    {
    ////////        foreach (DataTable dt in inputInfo.Tables)
    ////////        {
    ////////            foreach (DataColumn dc in dt.Columns)
    ////////            {
    ////////                foreach (DataRow dr in dt.Rows)
    ////////                {
    ////////                    switch (dc.ColumnName.ToLower())
    ////////                    {
    ////////                        case "af_row_id":
    ////////                            if (dr[dc.ColumnName].ToString() == "" || saveMode)
    ////////                            {
    ////////                                if (hashKey == "") hashKey = getHashKey();
    ////////                                dr[dc.ColumnName] =  hashKey;
    ////////                            }
    ////////                            break;
    ////////                        case "created_by":
    ////////                            if (dr[dc.ColumnName].ToString() == "" || saveMode)
    ////////                            {
    ////////                                //if (sysVar.ContainsKey("Current User"))
    ////////                                //    dr[dc.ColumnName] = sysVar["Current User"].ToString();
    ////////                                dr[dc.ColumnName] = Session["userid"].ToString();
    ////////                            }
    ////////                            break;
    ////////                        case "modified_at":
    ////////                            dr[dc.ColumnName] = System.DateTime.Now.ToUniversalTime().ToString();
    ////////                            break;
    ////////                        case "created_at":
    ////////                            if (dr[dc.ColumnName].ToString() == "" || saveMode)
    ////////                                dr[dc.ColumnName] = System.DateTime.Now.ToUniversalTime().ToString();
    ////////                            break;
    ////////                        case "modified_by":
    ////////                            dr[dc.ColumnName] = Session["userid"].ToString();
    ////////                            break;
    ////////                    }
    ////////                }
    ////////            }
    ////////        }
    ////////    }
    ////////    catch (Exception e)
    ////////    {
    ////////        LogWriter.WriteLog("Error in setDefaultValues. Error: " + e.Message);
    ////////    }
    ////////}
    #endregion
    private void loadAllVariables()//created by sanal on Oct 18, 2007 for sys var implementation
    {
        sysVar = new Hashtable();
        loadSystemVariables();        
        //loadPageVariables(this.Controls);
        if (dsePageInfo.Tables.Count > 0)
            loadPageVariables(dsePageInfo);
        GlobalValues.hsSysVar = sysVar;
    }
    private void loadPageVariables(DataSet dsInp)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        try
        {
            string tableName = ""; string pageId = "";            
            DataTable dt = dsInp.Tables["Page"];            
            foreach (DataRow dr in dt.Rows)
            {
                tableName = dr["page_table_name"].ToString();
                pageId = dr["page_id"].ToString();
                DataRow[] drs = dsInp.Tables["PageCtrl"].Select("page_id='" + dr["page_id"].ToString() + "'");
                for (int i = 0; i < drs.Length; i++)                
                    getControlValue(tableName, drs[i]["control_id"].ToString(), pageId);                
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in loadPageVariables function: " + e.Message);
        }
    }
    private void getControlValue(string tableName, string controlName, string pageId)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        Control cInp;
        DynamicDisplayI di = new DynamicDisplayI();
        cInp  = di.FindControl(this.Controls, pageId + "_" + controlName);
        di = null;
        tableName = tableName + "." + controlName;
        if (cInp != null)
        {
            switch (cInp.GetType().ToString())
            {
                case "System.Web.UI.WebControls.TextBox":
                    TextBox tb = (TextBox)cInp;
                    sysVar.Add(tableName, tb.Text);
                    break;
                case "System.Web.UI.WebControls.DropDownList":
                    DropDownList db = (DropDownList)cInp;
                    sysVar.Add(tableName, db.SelectedValue);
                    break;
                case "System.Web.UI.WebControls.CheckBox":
                    CheckBox cb = (CheckBox)cInp;
                    sysVar.Add(tableName, cb.Checked);
                    break;
                case "System.Web.UI.WebControls.CheckBoxList":
                    CheckBoxList cbl = (CheckBoxList)cInp;
                    //sysVar.Add(tableName, tb.se);
                    break;
                case "System.Web.UI.WebControls.RadioButton":
                    RadioButton rb = (RadioButton)cInp;
                    sysVar.Add(tableName, rb.Checked);
                    break;
                case "System.Web.UI.WebControls.RadioButtonList":
                    RadioButtonList rbl = (RadioButtonList)cInp;
                    //hInp.Add(tableName, tb.Text);
                    break;
            }
        }
    }
    private void loadPageVariables(ControlCollection mainControl)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        foreach (Control cc in mainControl)
        {
            if (cc.Controls.Count < 1)
            {
                if (cc.ID != null)
                    if (cc.Controls.Count < 1)
                        add2HashTable(cc, sysVar);
            }
            else
                loadPageVariables(cc.Controls);
        }
    }
    private void add2HashTable(Control cInp,Hashtable hInp)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        switch (cInp.GetType().ToString())
        {
            case "System.Web.UI.WebControls.TextBox":
                TextBox tb = (TextBox)cInp;
                hInp.Add(cInp.ID,tb.Text);
                break;
            case "System.Web.UI.WebControls.DropDownList":
                DropDownList db = (DropDownList)cInp;
                hInp.Add(cInp.ID, db.SelectedValue);
                break;
            case "System.Web.UI.WebControls.CheckBox":
                CheckBox cb = (CheckBox)cInp;
                hInp.Add(cInp.ID, cb.Checked);
                break;
            case "System.Web.UI.WebControls.CheckBoxList":
                CheckBoxList cbl = (CheckBoxList)cInp;
                //hInp.Add(cInp.ID, tb.se);
                break;
            case "System.Web.UI.WebControls.RadioButton":
                RadioButton rb = (RadioButton)cInp;
                hInp.Add(cInp.ID, rb.Checked);
                break;
            case "System.Web.UI.WebControls.RadioButtonList":
                RadioButtonList rbl = (RadioButtonList)cInp;
                //hInp.Add(cInp.ID, tb.Text);
                break;
        }
    }
    private object getVariableName(string variableName)
    {
        if (sysVar!=null)
            if (sysVar.ContainsKey(variableName))
                return sysVar[variableName];
        return null;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (SaveData())
        {
            string ret = getURL();//implemented by sanal on 13 Dec 2007
            if (ret != "")
                Response.Redirect(ret, true);
            else
                lbl_message.Text = "Data Inserted Successfully";
        }
        else
        {
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = "Data Insert not successful. Error: " + objMaster.DeleteMessage;
                objMaster.DeleteMessage = "";
            }
            else
            {
                lbl_message.Text = "Data Insert not successful. Error:" + ErrorMessage;
            }
        }
    }
    private string getURL()//implemented by sanal on 13 Dec 2007
    {
        try
        {
            return hfRequestURL.Value;
            //return "DisplayGrid.aspx?mn=" + Request.QueryString["mn"].ToString() + "&pgs_id=" + Request.QueryString["pgs_id"].ToString();
        }
        catch (Exception e)
        {
            return "";
        }        
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (UpdateData())
        {
            string ret = getURL();//implemented by sanal on 13 Dec 2007
            if (ret != "")
                Response.Redirect(ret, true);
            else
                lbl_message.Text = "Data Updated Successfully";
        }
        else
        {
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = "Data Update not successful. Error: " + objMaster.DeleteMessage;
                objMaster.DeleteMessage = "";
            }
            else
            {
                lbl_message.Text = "Data Update not successful. Error:" + ErrorMessage;
            }
        }
    }

    private bool UpdateData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPageSetId, frmObj, dsePageInfo,false);

        //setDefaultValues(dseInputInfo,false);

        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    
    protected void btnReset_Click(object sender, EventArgs e)
    {
        if (IsPostBack)
            Server.Transfer(Request.RawUrl,true);
    }
}
